<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	
if ( ! function_exists('form_checkbox'))
{
	function form_checkbox($name, $value = '', $checked = FALSE, $text = '', $id = null, $extra = null)
	{
		$str = "<input type='checkbox' name='".$name."' value='".$value."'";
		if($checked)
		{
			$str .= " checked";
		}
		if($text)
		{
			$id = $id ? $id : uniqid();
		}
		if($id)
		{
			$str .= " id='".$id."'";
		}
		$str .= ($extra ? " ".$extra : '').'>';
		if($id)
		{
			$str = '<label for="'.$id.'">'.$str.' '.$text.'</label>';
		}
		return $str;
	}
}
	
function form_dropdown2($name, $options, $selected = array(), $field_name1 = 'id', $field_name2 = 'name', $extra = null, $add_empty = false)
{
	$arr = array();
	if($add_empty)
	{
		$arr[''] = '';
	}
	foreach($options as $row)
	{
		$arr[$row[$field_name1]] = $row[$field_name2];
	}
	return form_dropdown($name, $arr, $selected, $extra);
}

function form_list_checkboxes($name, $arr, $selected = array(), $add_all = false)
{
	$out = '';
	if(!is_array($selected))
	{
		$selected = array();
	}
	$ids = array();
	foreach($arr as $k => $v)
	{
		$id = str_replace("]", "_", str_replace("[", "_", $name))."_".$k;
		$out .= form_checkbox($name, $k, in_array($k, $selected), $v, $id)."<br>\n";
		$ids[] = "'".$id."'"; 
	}
	if($add_all && count($ids))
	{
		$function_id = substr(uniqid(), 0, 4);
		$str = "\n<script language='javascript'>
function checkAll".$function_id."(arr, ch)
{
	for(var i = 0; i < arr.length; i++)
	{
		if(document.getElementById(arr[i])) document.getElementById(arr[i]).checked = ch;
	}
}
</script>\n";
		$str .= form_checkbox('', '', false, "<b>Все</b>", null, "onchange=\"checkAll".$function_id."([".implode(",", $ids)."], this.checked)\"")."<br>\n";
		$out = $str.$out;
	}
	return $out;
}

function form_list_checkboxes2($name, $arr, $selected = array(), $add_all = false, $field_name1 = 'id', $field_name2 = 'name')
{
	$arr2 = array();
	foreach($arr as $row)
	{
		$arr2[$row[$field_name1]] = $row[$field_name2];
	}
	return form_list_checkboxes($name, $arr2, $selected, $add_all);
}

function printOptionsUsers($users, $level = 0, $selected_id = 0, $no_view_id = null)
{
	foreach($users as $user)
	{
		if($user['id'] != $no_view_id)
		{
			echo "<option value='".$user['id']."' ".($selected_id == $user['id'] ? "selected" : '').">".str_repeat("&nbsp;", $level * 5).$user['fio']." (".$user['email'].")</option>";
		}
		if(@$user['children'] && is_array($user['children']) && count($user['children']))
		{
			printOptionsUsers($user['children'], $level + 1, $selected_id);
		}
	}
}

